//
//  M4SecondInfoViewController.swift
//  M4
//
//  Created by YuChuang on 2024/8/9.
//

import UIKit
import AddressBookUI

class M4SecondInfoViewController: M4BaseViewController {
    
    lazy var scrollView: UIScrollView = {
        let scroll = UIScrollView()
        scroll.backgroundColor = .white
        scroll.contentSize.width = M4ScreenWidth
        scroll.showsVerticalScrollIndicator = false
        scroll.showsHorizontalScrollIndicator = false
        return scroll
    }()
    
    lazy var tipImageView: M4InfosTopKycTipImageView = {
        
        let view = UINib(nibName: "M4InfosTopKycTipImageView", bundle: nil).instantiate(withOwner: self).last as! M4InfosTopKycTipImageView
        view.M4TipimageView.image = UIImage(named: "img_schedule2")
        
        view.setStyledCreditText(amountText: "$ 20,000",typestr: 2)
        
        return view
    }()
    
    
    
    lazy var addButton: M4InfoScontactoParaView = {
        let view = UINib(nibName: "M4InfoScontactoParaView", bundle: nil).instantiate(withOwner: self).last as! M4InfoScontactoParaView
        view.didTapAgregarHandle = {
            self.addContact()
        }
        return view
    }()
    
    
    
    
    
    

 
    
    lazy var bottomView: M4InfosBottomView = {
        let view = M4InfosBottomView()
        view.m4View.c = self
        view.m4BottomButtonBlock = { button in
            self.view.endEditing(true)
            //提交信息
//            let vc = M4ThirdInfoViewController()
//            self.navigationController?.pushViewController(vc, animated: true)
//            button.M4EventUnavailable = false
            self.M4SubmitSecondInfoNet()
        }
        return view
    }()
    
    private var m4contactTFViews: [M4ContactInputView] = []
    
    private var m4chooseTag: Int = 0
    
    private var m4enterTime: Int = 0
    
    private var m4RelationKeys: [String] = ["Mjpb", "LIy", "gKsf", "tjfs", "gkjd"]
    
    private var m4PhoneKeys: [String] = ["YlWc", "XSGXEL", "bkKd", "Bjhcsef", "eJcb"]
    
    private var m4NameKeys: [String] = ["Plu", "MPhPc", "ogsf", "NJdGfc", "oVxxs"]
    let maxContacts = 4
    let defaultContacts = 2
    override func viewDidLoad() {
        super.viewDidLoad()
        bottomView.m4submitButton.setTitle("Presentar", for: .normal)
        m4enterTime = Int(Date().timeIntervalSince1970 * 1000)
        view.backgroundColor = .white
        M4NavBarColor = .white
        M4BackIcon = "icon_back_black"
        M4NavTitle(M4Title: "Información de contacto", M4NavTitleColor: COLOR_333333)
        m4updateUI()
    }
    
    override func M4BackClick(sender: UIButton) {
        view.endEditing(true)
        M4InfosPageBack()
        sender.M4EventUnavailable = false
    }
    
    private func m4updateUI() {
        view.addSubview(scrollView)
        scrollView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(M4NavigationFullHeight()+0.5)
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-M4SafeDistanceBottom())
        }
        scrollView.addSubview(tipImageView)
        tipImageView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(15)
            make.left.right.equalToSuperview()
            make.width.equalTo(M4ScreenWidth)
        }
//        M4CreditStatusManager.m4CreditShare.m4isContactCount = 5
//        for i in 0..<M4CreditStatusManager.m4CreditShare.m4isContactCount {
//            let view = UINib(nibName: "M4ContactInputView", bundle: nil).instantiate(withOwner: self).last as! M4ContactInputView
//            m4contactTFViews.append(view)
//            view.M4ContactItemButton.tag = i
//            view.M4ContactItemMobileTF.tag = i
//            view.M4ContactItemNameTF.tag = i
//            view.M4ContactItemTitle.text = i == 0 ? "Padre/Madre" : "Amigo"
//            scrollView.addSubview(view)
//            view.snp.makeConstraints { make in
//                make.top.equalTo(tipImageView.snp.bottom).offset(110 * i)
//                make.left.right.equalToSuperview()
//                make.height.equalTo(110)
//                make.width.equalTo(M4ScreenWidth)
//            }
//            if i == M4CreditStatusManager.m4CreditShare.m4isContactCount - 1 {
//                scrollView.addSubview(bottomView)
//                bottomView.snp.makeConstraints { make in
//                    make.top.equalTo(view.snp.bottom).offset(20)
//                    make.left.right.equalToSuperview()
//                    make.bottom.equalToSuperview().offset(-20)
//                    make.width.equalTo(M4ScreenWidth)
//                }
//            }
//            view.M4ContactItemButton.addTarget(self, action: #selector(M4SecondItemTap(sender:)), for: .touchUpInside)
//        }
        
        
     
        setupContactViews()
        
        
    }
    
    func setupContactViews() {
        for i in 0..<defaultContacts {
            let view = createContactView(at: i, canDelete: false)
            m4contactTFViews.append(view)
            addContactView(view, index: i)
        }

        // 添加按钮视图
        scrollView.addSubview(addButton)
       
        addButton.snp.makeConstraints { make in
            make.top.equalTo(m4contactTFViews.last!.snp.bottom).offset(20)
            make.left.equalTo(scrollView).offset(16)
            make.right.equalTo(scrollView).offset(-16)
//            make.height.equalTo(120)
        }

        scrollView.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.top.equalTo(addButton.snp.bottom).offset(20)
            make.left.right.bottom.equalToSuperview()
            make.width.equalTo(M4ScreenWidth)
        }
    }
    
    func createContactView(at index: Int, canDelete: Bool) -> M4ContactInputView {
                    let view = UINib(nibName: "M4ContactInputView", bundle: nil).instantiate(withOwner: self).last as! M4ContactInputView
        view.M4ContactItemButton.tag = index
        view.M4ContactItemMobileTF.tag = index
        view.M4ContactItemNameTF.tag = index
        view.M4ContactItemTitle.text = index == 0 ? "Padre/Madre/Cónyuge" : index == 1 ? "Amigo" :"Otros contactos \(index+1)"
        view.iccuotaTip.isHidden = true
        view.peopleTopH.constant = 20
        if index == 3 {
            view.iccuotaTip.image = UIImage.init(named: "shape_b")

        }else{            view.iccuotaTip.image = UIImage.init(named: "shape_a")
}

    
        if canDelete {
            view.iccuotaTip.isHidden = false
            view.peopleTopH.constant = 48

            let deleteButton = UIButton.init(type: .custom)
            deleteButton.setImage(UIImage.init(named: "icon_delete"), for: .normal)
            view.addSubview(deleteButton)
            deleteButton.snp.makeConstraints { make in
                make.right.equalToSuperview().inset(15)
                make.top.equalToSuperview().inset(40)

                make.size.equalTo(CGSize(width: 24, height: 24))
            }
            deleteButton.M4EventUnavailable = false

            deleteButton.addTarget(self, action: #selector(removeContact(_:)), for: .touchUpInside)
            deleteButton.tag = index
        }
        view.M4ContactItemButton.addTarget(self, action: #selector(M4SecondItemTap(sender:)), for: .touchUpInside)
        return view
    }
    
  
    
    @objc func addContact() {
        let currentCount = m4contactTFViews.count
        guard currentCount < maxContacts else { return }

        let newIndex = currentCount
        let view = createContactView(at: newIndex, canDelete: true)
        m4contactTFViews.append(view)
        addContactView(view, index: newIndex)

        updateAddButtonPosition()
        updateBottomViewPosition()
        
        updateAddButtonState()
        self.addButton.agregarbtn.M4EventUnavailable = false
        // 强制 layout 更新 scrollView 的 contentSize
        scrollView.layoutIfNeeded()
    }
    
    

    
    func updateAddButtonState() {
        // 控制 addButton 显示或隐藏
        if m4contactTFViews.count < maxContacts {
            if addButton.superview == nil {
                scrollView.addSubview(addButton)
            }
            addButton.isHidden = false

            if m4contactTFViews.count == 2 {
                addButton.changcontrnt1(is3: false)

            }else{
                addButton.changcontrnt1(is3: true)

            }
            
            
            addButton.snp.remakeConstraints { make in
                make.top.equalTo(m4contactTFViews.last!.snp.bottom).offset(20)
                make.left.equalTo(scrollView).offset(16)
                make.right.equalTo(scrollView).offset(-16)
            }

            // bottomView 位置更新跟随 addButton
            bottomView.snp.remakeConstraints { make in
                make.top.equalTo(addButton.snp.bottom).offset(20)
                make.left.right.equalToSuperview()
                make.bottom.equalToSuperview().offset(-20)
            }

        } else {
            // 达到最大联系人数，隐藏 addButton
            addButton.removeFromSuperview()

            // bottomView 跟随最后一个 contact view
            bottomView.snp.remakeConstraints { make in
                make.top.equalTo(m4contactTFViews.last!.snp.bottom).offset(20)
                make.left.right.equalToSuperview()
                make.bottom.equalToSuperview().offset(-20)
            }
        }
    }
    
    func updateAddButtonPosition() {
        addButton.snp.remakeConstraints { make in
            make.top.equalTo(m4contactTFViews.last!.snp.bottom).offset(20)
            make.left.equalTo(scrollView).offset(16)
            make.right.equalTo(scrollView).offset(-16)
        }
    }

    func updateBottomViewPosition() {
        bottomView.snp.remakeConstraints { make in
            make.top.equalTo(addButton.snp.bottom).offset(20)
            make.left.right.bottom.equalToSuperview()
            make.width.equalTo(M4ScreenWidth)
        }
    }
    
//    @objc func removeContact(_ sender: UIButton) {
    @objc func removeContact(_ sender: UIButton) {
        sender.M4EventUnavailable = false

        guard let viewToRemove = sender.superview as? M4ContactInputView,
              let index = m4contactTFViews.firstIndex(of: viewToRemove),
              index >= defaultContacts else {
            return
        }

        viewToRemove.removeFromSuperview()
        m4contactTFViews.remove(at: index)
        // 重新布局剩余视图
        for (i, view) in m4contactTFViews.enumerated() {
//            view.M4ContactItemTitle.text = i == 0 ? "Padre/Madre" : (i == 1 ? "Amigo" : "Amigo")
            view.M4ContactItemButton.tag = i
            view.M4ContactItemMobileTF.tag = i
            view.M4ContactItemNameTF.tag = i
            view.M4ContactItemTitle.text = i == 0 ? "Padre/Madre/Cónyuge" : i == 1 ? "Amigo" :"Otros contactos \(i+1)"
            view.iccuotaTip.isHidden = true
            view.peopleTopH.constant = 20
            if i == 3 {
                view.iccuotaTip.image = UIImage.init(named: "shape_b")

            }else if i == 2{
                view.iccuotaTip.image = UIImage.init(named: "shape_a")
    }
            
            if (i == 3 || i == 2) {
                view.iccuotaTip.isHidden = false
                view.peopleTopH.constant = 48
            }
            view.snp.remakeConstraints { make in
                if i == 0 {
                    make.top.equalTo(tipImageView.snp.bottom)
                    make.height.equalTo(209-28)

                } else if i == 1{
                    make.height.equalTo(209-28)
                    make.top.equalTo(m4contactTFViews[i - 1].snp.bottom)

                } else {
                    make.top.equalTo(m4contactTFViews[i - 1].snp.bottom)
                    make.height.equalTo(209)

                }
                
                
               
                make.left.right.equalToSuperview()
            }
        }
        updateAddButtonState()

        updateAddButtonPosition()
        // 后续逻辑同上...
    }

//        @objc func removeContact(_ sender: UIButton) {
//            sender.M4EventUnavailable = false
//
//            let index = sender.tag
//            guard index >= defaultContacts, index < m4contactTFViews.count else { return }
//
//            let viewToRemove = m4contactTFViews[index]
//            viewToRemove.removeFromSuperview()
//            m4contactTFViews.remove(at: index)
//
//            // 重新更新所有视图的约束与 tag
//            for (i, view) in m4contactTFViews.enumerated() {
//                view.tag = i
//                view.M4ContactItemButton.tag = i
//                view.M4ContactItemMobileTF.tag = i
//                view.M4ContactItemNameTF.tag = i
//                view.M4ContactItemTitle.text = i == 0 ? "Padre/Madre" : "Amigo"
//                view.snp.remakeConstraints { make in
//                    if i == 0 {
//                        make.top.equalTo(tipImageView.snp.bottom)
//                    } else {
//                        make.top.equalTo(m4contactTFViews[i - 1].snp.bottom)
//                    }
//                    make.left.right.equalToSuperview()
//                    make.height.equalTo(110)
//                }
//            }
//
//            updateAddButtonPosition()
//            updateBottomViewPosition()
//            scrollView.layoutIfNeeded()
//        }
    
//    func updateAddButtonPosition() {
//        addButton.snp.remakeConstraints { make in
//            make.top.equalTo(m4contactTFViews.last!.snp.bottom).offset(20)
//            make.centerX.equalToSuperview()
//        }
//    }
    
    func addContactView(_ view: M4ContactInputView, index: Int) {
//        self.addButton.M4EventUnavailable = false
        self.addButton.agregarbtn.M4EventUnavailable = false
           
        scrollView.addSubview(view)
        view.snp.makeConstraints { make in
            if index == 0 {
                make.top.equalTo(tipImageView.snp.bottom).offset(0)
                make.height.equalTo(209-28)
            } else if index == 1{
                make.height.equalTo(209-28)
                make.top.equalTo(m4contactTFViews[index - 1].snp.bottom)

            } else {
                make.top.equalTo(m4contactTFViews[index - 1].snp.bottom)
                make.height.equalTo(209)

            }
            make.left.right.equalToSuperview()
        }
    }

    
    private func M4SubmitSecondInfoNet() {
        for i in 0..<m4contactTFViews.count {
            if m4contactTFViews[i].M4ContactItemNameTF.text?.count == 0 {
                self.view.makeToast("Por favor, elija el nombre del contacto", position: .center)
                self.bottomView.m4submitButton.M4EventUnavailable = false
                return
            }
            else if m4contactTFViews[i].M4ContactItemMobileTF.text?.count == 0 {
                self.view.makeToast("Por favor, elija el número de teléfono de contacto", position: .center)
                self.bottomView.m4submitButton.M4EventUnavailable = false
                return
            }
        }
        let m4endTime = Int(Date().timeIntervalSince1970 * 1000) - m4enterTime
        var param1: [String : Any] = ["FeqKW": M4UserDataManager.m4UserShare.M4Itemcode, "YOcQCpfM": "ESP", "KKo": M4UserDataManager.m4UserShare.M4ProductCode, "CAdRudKdvHw": M4UserDataManager.m4UserShare.M4Token, "Zucl": 3, "HyHzRWokXbo": m4endTime ]
        for k in 0..<m4contactTFViews.count {
            param1[m4RelationKeys[k]] = k == 0 ? 1 : 5
            param1[m4PhoneKeys[k]] = m4contactTFViews[k].M4ContactItemMobileTF.text
            param1[m4NameKeys[k]] = m4contactTFViews[k].M4ContactItemNameTF.text
        }
        M4NetworkManager().M4Request(M4NetworkTarget.M4_targetType(.m4submitCreditInfo, .post, params: param1)) { model in
            self.bottomView.m4submitButton.M4EventUnavailable = false
            if model.code == 1 {
                let vc = M4ThirdInfoViewController()
                self.navigationController?.pushViewController(vc, animated: true)
                self.uploadData()
            }
            else {
                self.view.makeToast(model.message, position: .center)
            }
        }
    }
    
    var phoneData1: (String, Int, Int) = ("", 0, 0)
    var phoneData2: (String, Int, Int) = ("", 0, 0)
    var nameData1: (String, Int, Int) = ("", 0, 0)
    var nameData2: (String, Int, Int) = ("", 0, 0)
    
    func uploadData() {
        let params: [[String:Any]] = [
            [
                "adga" : 4001,
                "sdqw" : inTime,
                "hgjyj" : Int(Date().timeIntervalSince1970 * 1000) ,
            ],
            [
                "adga" : 4002,
                "faqwr" : phoneData1.0,
                "gsde" : phoneData1.2 - phoneData1.1,
                "hghrt" : phoneData2.0,
                "akgjrt" : phoneData2.2 - phoneData2.1
            ],
            [
                "adga" : 4003,
                "faqwr" : nameData1.0,
                "gsde" : nameData1.2 - nameData1.1,
                "hghrt" : nameData2.0,
                "akgjrt" : nameData2.2 - nameData2.1
            ],
        ]
        M4HiddenPointDataManager.M4UploadHiddenPoint(type: .Contact, paramsKey: "eqet", params: params, complete: nil)
    }
}

extension M4SecondInfoViewController: UINavigationControllerDelegate, ABPeoplePickerNavigationControllerDelegate {
    
    @objc private func M4SecondItemTap(sender: UIButton) {
        m4chooseTag = sender.tag
        let con = ABPeoplePickerNavigationController()
        con.delegate = self
        con.peoplePickerDelegate = self
        con.modalPresentationStyle = .fullScreen
        self.present(con, animated: true)
        sender.M4EventUnavailable = false
    }
    
    func peoplePickerNavigationController(_ peoplePicker: ABPeoplePickerNavigationController, didSelectPerson person: ABRecord) {
        
        let firstName = ABRecordCopyValue(person, kABPersonFirstNameProperty)?.takeRetainedValue() as? String ?? ""
        let lastName = ABRecordCopyValue(person, kABPersonLastNameProperty)?.takeRetainedValue() as? String ?? ""
        let fullName = firstName + " " + lastName
        var phone: String = ""
        
        if let phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty)?.takeRetainedValue() as? ABMultiValue {
            for index in 0..<ABMultiValueGetCount(phoneNumbers) {
                let phoneNumber = ABMultiValueCopyValueAtIndex(phoneNumbers, index)?.takeRetainedValue() as? String
                print("mobole: \(phoneNumber ?? "")")
                phone = phoneNumber ?? ""
                break
            }
        }
        
        if !M4VerifyMobileFormat(mobile: phone, isSelect: true) {
           return
        }
        
        m4contactTFViews[m4chooseTag].M4ContactItemNameTF.text = fullName
        m4contactTFViews[m4chooseTag].M4ContactItemMobileTF.text = phone
        if m4chooseTag == 0 {
            phoneData1.0 = phone
            nameData1.0 = fullName
        } else if m4chooseTag == 1 {
            phoneData2.0 = phone
            nameData2.0 = fullName
        }
    }
    
    //改为手动输入
    func peoplePickerNavigationControllerDidCancel(_ peoplePicker: ABPeoplePickerNavigationController) {
        m4contactTFViews.forEach { view in
            view.M4ContactItemButton.isHidden = true
            view.M4ContactItemNameTF.isUserInteractionEnabled = true
            view.M4ContactItemMobileTF.isUserInteractionEnabled = true
            view.M4ContactItemMobileTF.delegate = self
            view.M4ContactItemNameTF.placeholder = "Nombre"
            view.M4ContactItemNameTF.delegate = self
            view.M4ContactItemMobileTF.placeholder = "Número de teléfono"
        }
    }
    
    private func M4VerifyMobileFormat(mobile: String, isSelect: Bool) -> Bool {
        //M4CreditStatusManager.m4CreditShare.m4phonePattern
        for k in 0..<m4contactTFViews.count {
            if isSelect {
                if mobile == m4contactTFViews[k].M4ContactItemMobileTF.text {
                    self.view.makeToast("El número de teléfono de contacto no debe ser el mismo", position: .center)
                    return false
                }
            }
            else {
                if k != m4chooseTag {
                    if mobile == m4contactTFViews[k].M4ContactItemMobileTF.text {
                        self.view.makeToast("El número de teléfono de contacto no debe ser el mismo", position: .center)
                        return false
                    }
                }
            }
            
        }
        
        var mobileString = mobile.replacingOccurrences(of: " ", with: "")
        mobileString = mobileString.replacingOccurrences(of: "(", with: "")
        mobileString = mobileString.replacingOccurrences(of: ")", with: "")
        mobileString = mobileString.replacingOccurrences(of: "-", with: "")
        mobileString = mobileString.replacingOccurrences(of: "+", with: "")
        if mobileString.prefix(3) == "+52" {
            mobileString.removeFirst(3)
        }
        else if mobileString.prefix(2) == "52"{
            mobileString.removeFirst(2)
        }
        
//        if mobileString.count != 10 {
//            self.view.makeToast("El número de teléfono móvil del contacto está mal formado", position: .center)
//            return false
//        }
//        
        if mobileString == M4UserDataManager.m4UserShare.M4UserMobile {
            self.view.makeToast("El número de teléfono móvil del contacto no puede registrarse para ti", position: .center)
            return false
        }
        
        if mobile.count > 16 || !M4IsPatternCharacters(in: mobile, pattern: M4CreditStatusManager.m4CreditShare.m4phonePattern) {
            self.view.makeToast("El número de teléfono móvil del contacto está mal formado", position: .center)
            return false
        }
        
        return true
    }
    
    func M4IsPatternCharacters(in string: String, pattern: String) -> Bool {
        let expression = try? NSRegularExpression(pattern: pattern, options: [])
        let numberOfCharacters = expression?.numberOfMatches(in: string, options: [], range: NSMakeRange(0, string.count))

        return numberOfCharacters == 0 ? false : true
      }
    
}

extension M4SecondInfoViewController: UITextFieldDelegate {
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        m4chooseTag = textField.tag
        if string == "" { return true }
        if textField == m4contactTFViews[m4chooseTag].M4ContactItemMobileTF {
            guard let textString = textField.text else {return true}
            let length = textString.count + string.count - range.length
            if textString.prefix(2) == "52" && length <= 12 {
                return true
            }
            else if length <= 10 {
                return true
            }
            return false
        }
        return true
    }
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        if textField.tag == 0 {
            if textField == m4contactTFViews[textField.tag].M4ContactItemMobileTF {
                phoneData1.1 = Int(Date().timeIntervalSince1970 * 1000)
            } else if textField == m4contactTFViews[textField.tag].M4ContactItemNameTF {
                nameData1.1 = Int(Date().timeIntervalSince1970 * 1000)
            }
        } else if textField.tag == 1 {
            if textField == m4contactTFViews[textField.tag].M4ContactItemMobileTF {
                phoneData2.1 = Int(Date().timeIntervalSince1970 * 1000)
            } else if textField == m4contactTFViews[textField.tag].M4ContactItemNameTF {
                nameData2.1 = Int(Date().timeIntervalSince1970 * 1000)
            }
        }
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        m4chooseTag = textField.tag
        if textField == m4contactTFViews[m4chooseTag].M4ContactItemMobileTF {
            if !M4VerifyMobileFormat(mobile: textField.text ?? "", isSelect: false) {
                m4contactTFViews[m4chooseTag].M4ContactItemMobileTF.text = ""
               return
            }
        }
        
        
        if textField.tag == 0 {
            if textField == m4contactTFViews[textField.tag].M4ContactItemMobileTF {
                phoneData1.2 = Int(Date().timeIntervalSince1970 * 1000)
                phoneData1.0 = textField.text ?? ""
            } else if textField == m4contactTFViews[textField.tag].M4ContactItemNameTF {
                nameData1.2 = Int(Date().timeIntervalSince1970 * 1000)
                nameData1.0 = textField.text ?? ""
            }
        } else if textField.tag == 1 {
            if textField == m4contactTFViews[textField.tag].M4ContactItemMobileTF {
                phoneData2.2 = Int(Date().timeIntervalSince1970 * 1000 )
                phoneData2.0 = textField.text ?? ""
            } else if textField == m4contactTFViews[textField.tag].M4ContactItemNameTF {
                nameData2.2 = Int(Date().timeIntervalSince1970 * 1000)
                nameData2.0 = textField.text ?? ""
            }
        }
    }
    
}

